var config = require('../../config');
Page({
  data: {
    totalPage: 0,
    nowPage: 1,
    list: [{
      image_url: '/images/blank.jpg'
    }],
    loading_display: 'display: none;',
    endMsg: ''
  },
  onLoad: function (option) {
    this.getTotalPage();
    this.getPostList();
  },
  getTotalPage: function () {
    var that = this;
    wx.request({
      url: config.total_page_url,
      success: function (res) {
        if (res.statusCode != 200) {
          wx.showToast({
            title: '网络请求发生错误',
          })
        } else {
          that.data.totalPage = res.data
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '网络请求发生错误',
        })
      },
      complete: function (res) {
      }
    })
  },
  getPostList: function () {
    var that = this;
    wx.request({
      url: config.post_list_url,
      data: {
        page: that.data.nowPage
      },
      success: function (res) {
        if (res.statusCode != 200) {
          wx.showToast({
            title: '网络请求发生错误',
          })
        } else {
          that.data.postList = res.data
          that.setData({
            list: res.data
          });
        }
      }
    })
  },
  onReachBottom: function () {
    var self = this;

    // loading
    self.setData({
      loading_display: 'display: block;'
    });

    var page = parseInt(self.data.nowPage + 1);
    if (page <= self.data.totalPage) {
      wx.request({
        url: config.post_list_url,
        data: {
          page: page
        },
        success: function (res) {
          if (res.statusCode == 200) {
            var list = self.data.list;
            Array.prototype.push.apply(list, res.data);
            self.data.list = list;
            self.data.nowPage = page;
            self.setData({
              list: list,
              loading_display: 'display:none;'
            });
          } else {
            self.setData({
              loading_display: 'display:none;'
            });
            wx.showToast({
              title: '网络请求失败，请重试',
            })
          }
        }
      })
    } else {
      self.setData({
        loading_display: 'display:none;',
        endMsg: '已经到底了，没有更多文章了',
      });
    }
  },
  onShareAppMessage: function () {
    return {
      title: '爱美文，精典美文与诗歌收集珍藏。',
      path: '/pages/jx/jx',
      imageUrl: '/images/xiaochengxu.jpg',
    };
  }
})